package com.zy.yun.controller.common;


import com.zy.yun.base.annotation.NotNullPara;
import com.zy.yun.base.common.RestResult;
import com.zy.yun.base.constant.ReturnCodeMsgEnum;
import com.zy.yun.base.util.DateUtil;
import com.zy.yun.base.util.UUIDUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

/**
 * @Auther: wangyanwei
 * @Date: 2019/4/22 09:32
 * @Description: 文件管理
 */
@Api(description = "文件管理",tags = "文件管理")
@Slf4j
@Controller
@RequestMapping("file")
public class FileController {

    /**
     * 文件存储路径
     */
    @Value("${file.save-path}")
    private String fileSavePath;

    /**
     * 多长时间创建一个新的文件夹
     */
    @Value("${file.create-dir-days}")
    private Integer fileCreateDirDays;

    /**
     * 文件服务器地址
     */
    @Value("${file.server-addr}")
    private String fileServerAddr;


    /**
     * 功能描述:文件上传
     *
     * @auther: wangyanwei
     * @date: 2019/4/22 9:33
     * @param:
     * @return:
     */
    @ApiOperation("doc、excel等文件上传接口")
    @ResponseBody
    @PostMapping("fileUpload")
    public RestResult fileUpload(@RequestParam(value = "file", required = true) MultipartFile file) {
        RestResult restResult = new RestResult();

        if (file.isEmpty()) {
            return RestResult.buildError("文件内容为空！");
        }

        String newFilenameBase = UUIDUtils.random();
        //得到文件后辍
        String originalFileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //文件新名称
        String newFilename = newFilenameBase + originalFileExtension;

        Integer count = DateUtil.getTodateString() != null ? Integer.parseInt(DateUtil.getTodateString()) : 0;
        String dirName = null;
        //根据天数，判断是否需要创建新的目录
        if (count % fileCreateDirDays == 0) {
            dirName = DateUtil.getTodateString();
        } else {
            dirName = DateUtil.getStrDate(String.valueOf(fileCreateDirDays)).replaceAll("-", "");

        }
        String basePath = fileSavePath + "/" + dirName;
        //判断目录是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs(); //级联创建目录
        }
        //文件路径
        String path = basePath + "/" + newFilename;

        try {
            //写入文件
            file.transferTo(new File(path));
            //拼接前端访问文件全路径
            String imageUrl = fileServerAddr + dirName + "/" + newFilename;

            restResult.setResult(imageUrl);
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getMsg());
            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_SUCCESS.getCode());


        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
            restResult.setMsg(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getMsg());
            restResult.setCode(ReturnCodeMsgEnum.DATA_SAVE_FAIL.getCode());
        }
        return restResult;

    }


    /**
     * 功能描述: 大文件分割上传
     * @param:
     * @return:
     * @auther: wangyanwei
     * @date: 2019/5/12 18:09
     */

    @ResponseBody
    @ApiOperation("大文件分割上传")
    @NotNullPara({"fileName"})
    @RequestMapping("bigFileUpload")
    public RestResult bigFileUpload(@RequestParam("file") MultipartFile file, String fileName) throws IOException {
        RestResult restResult = new RestResult();

        //判断文件是否为空
        if(file.isEmpty()){
            return RestResult.buildError();
        }

        Integer count = DateUtil.getTodateString() != null ? Integer.parseInt(DateUtil.getTodateString()) : 0;
        String dirName = null;
        //根据天数，判断是否需要创建新的目录
        if (count % fileCreateDirDays == 0) {
            dirName = DateUtil.getTodateString();
        } else {
            dirName = DateUtil.getStrDate(String.valueOf(fileCreateDirDays)).replaceAll("-", "");

        }
        String basePath = fileSavePath + "/" + dirName;
        //判断目录是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs(); //级联创建目录
        }
        //文件路径
        String path = basePath + "/" + fileName;

        File fl = new File(path);

        RandomAccessFile raf=new RandomAccessFile(fl, "rw");
        //将写文件指针移到文件尾。
        raf.seek(raf.length());
        InputStream inputStream = file.getInputStream();

        int len=1024;
        byte[] bytes=new byte[len];

        while (inputStream.read(bytes,0,len)>0){
            raf.write(bytes);
        }


//        raf.writeBytes("first test RandomAccessFile append \r\n");
        raf.close();




        return restResult;
    }

}
